import bll.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Student s1 = new Student("1002", "刘德华");
        Student s2 = new Student("1003", "张学友");
        Class<?> c1 = s1.getClass();//通过对象获取对象所属的类类型
        Class<?> c2 = s2.getClass();//通过对象获取对象所属的类类型
        if (c1 == c2) {
            System.out.println("s1和s2是同一个类的对象");
        }
        // 通过反射机制，获取c1类的所有方法，包含继承下来的方法
        Method[] methods = c1.getMethods();
        for (var method : methods) {
            System.out.println(method.getName());
        }
        // 通过反射机制，获取c1类的数据成员（Declared表示只获取声明的数据成员，不包括继承下来的）
        Field[] fields = c1.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }
        System.out.println("---------------通过字符串加载一个类并实例化为对象-----------------------------");
        // 通过类的字符串路径名动态地记载一个类到内存
        Class<?> c = Class.forName("bll.Student");
        Object o = c.getConstructors()[0].newInstance("1002", "刘德华");
        if (o instanceof Student) {
            System.out.println("学生类型");
        }
        Constructor[] constructors = c.getConstructors();
        Student student = (Student) constructors[0].newInstance("1001", "dsx");
        System.out.println(student);//等价于System.out.println(student.toString());
        System.out.println("--------------反射获取对象所属类的所有方法-------------");
        methods = student.getClass().getMethods();
        System.out.println("--------------反射调用get函数-------------");
        for (var method : methods) {
            if (method.getName().contains("get")) {
                System.out.println(method.invoke(student));
            }
        }
        System.out.println("---------------------------");
        c = Class.forName("bll.Student");
        Method method = c.getMethod("setValue", String.class, String.class);
        student = (Student) c.getConstructors()[0].newInstance("1002", "刘德华");
        System.out.println(student);
        method.invoke(student, "1004", "张学友");
        System.out.println(student);
    }
}